package com.szgd.service.schedule;

import com.szgd.bean.SysDict;
import com.szgd.dao.ecdata.schedule.MainWorkScheduleMapper;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.project.BidService;
import com.szgd.service.project.SiteService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.service.sys.SysDictService;
import com.szgd.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MainWorkScheduleService extends SimulateBaseService {

    @Autowired
    MainWorkScheduleMapper mainWorkScheduleMapper;
    @Autowired
    SiteService siteService;
    @Autowired
    BidService bidService;
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;
    @Autowired
    SysDictService sysDictService;

    public List<Map<String,Object>> getMainWorkScheduleList(Map<String, Object> params)
    {
        return  mainWorkScheduleMapper.getMainWorkScheduleList(params);
    }


    public Map<String,Object> getChart(Map<String, Object> params)
    {
        Map<String,Object> res = new HashMap<>();
        List<String> legend = new ArrayList<>();
        List<String> xAxis = new ArrayList<>();
        List<List<Double>> series = new ArrayList<>();
        List<List<Double>> current = new ArrayList<>();
        List<List<Double>> cumulative = new ArrayList<>();
        List<List<Double>> total = new ArrayList<>();
        String flag = params.get("flag")==null?"":params.get("flag").toString().replace("null","");
        String statisticsTimeTable = params.get("statisticsTimeTable")==null?"":params.get("statisticsTimeTable").toString().replace("null","");
        if(statisticsTimeTable.length() > 0){
            params.put("statisticsTime",statisticsTimeTable);
        }
        List<String> siteIds = this.getSiteIds(params);
        params.put("siteIds",siteIds);
        if(flag.length() == 0){
            params.put("projectName",null);
            params.put("PARENT_CODE","SITE_PROJECT_NAME");
            List<SysDict> legendList = sysDictService.getAllSysDict(params);
            for(SysDict sysDict : legendList){
                legend.add(sysDict.getDictValue());
            }
        }else if(flag.equalsIgnoreCase("whjg")){
            params.put("projectName","围护结构");
            legend.add("地下连续墙（幅）");
            legend.add("钻孔灌注桩（含格构柱）（根）");
            legend.add("SMW桩（根）");
        }else if(flag.equalsIgnoreCase("tfkw")){
            params.put("projectName","土方开挖");
            legend.add("土方开挖（立方）");
            legend.add("钢支撑架设（根）");
        }else if(flag.equalsIgnoreCase("ztjg")){
            params.put("projectName","主体结构");
            legend.add("垫层（段）");legend.add("底板（段）");
            legend.add("中板（段）");legend.add("顶板（段）");
        }
        params.put("source",0);
        int xAxisNum = this.getXAxisNum(params).size();
        List<Map<String,Object>> chartList = mainWorkScheduleMapper.getChart(params);
        for(int i = 0; i < legend.size(); i++){
            List<Double> rateTemp = new ArrayList<>();
            List<Double> curTemp = new ArrayList<>();
            List<Double> cumTemp = new ArrayList<>();
            List<Double> totTemp = new ArrayList<>();
            int start = i * xAxisNum;
            int end = start + xAxisNum;
            for(int j = start; j < end; j++){
                if(j < xAxisNum){
                    String siteName = chartList.get(j).get("siteName")==null?"":chartList.get(j).get("siteName").toString();
                    xAxis.add(siteName);
                }
                rateTemp.add(Double.valueOf(chartList.get(j).get("completeRate").toString()));
                curTemp.add(Double.valueOf(chartList.get(j).get("current").toString()));
                cumTemp.add(Double.valueOf(chartList.get(j).get("cumulative").toString()));
                totTemp.add(Double.valueOf(chartList.get(j).get("total").toString()));
            }
            series.add(rateTemp);
            current.add(curTemp);
            cumulative.add(cumTemp);
            total.add(totTemp);
        }
        res.put("legend",legend);
        res.put("xAxis",xAxis);
        res.put("series",series);
        res.put("current",current);
        res.put("cumulative",cumulative);
        res.put("total",total);
        return res;
    }

    public List<String> getSiteIds(Map<String, Object> params){
        List<String> siteIds = new ArrayList<>();
        Object idObject = params.get("siteId");
        if (idObject != null) {
            if (idObject instanceof String || idObject instanceof Integer) {
                siteIds.add(idObject.toString());
            } else if (idObject instanceof ArrayList) {
                siteIds = (ArrayList<String>) idObject;
            }
        }
        return siteIds;
    }

    public List<String> getBidIds(Map<String, Object> params){
        List<String> bidIds = new ArrayList<>();
        Object idObject = params.get("bidId");
        if (idObject != null) {
            if (idObject instanceof String) {
                bidIds.add(idObject.toString());
            } else if (idObject instanceof ArrayList) {
                bidIds = (ArrayList<String>) idObject;
            }
        }
        return bidIds;
    }

    public Map<String,Object> getChart2(Map<String, Object> params)
    {
        List<String> bidIds = this.getBidIds(params);
        params.put("bidIds",bidIds);
        Map<String,Object> res = new HashMap<>();
        List<String> legend = new ArrayList<>();
        legend.add("地下连续墙（幅）");legend.add("钻孔灌注桩（含格构柱）（根）");legend.add("咬合桩（根）");
        legend.add("SMW桩（根）");legend.add("旋喷桩（根）");
        legend.add("双/三轴搅拌桩（组）");legend.add("降水井（口）");
        legend.add("土方开挖（立方）");legend.add("钢支撑架设（根）");
        legend.add("垫层（段）");legend.add("底板（段）");
        legend.add("中板（段）");legend.add("顶板（段）");
        List<String> legends = new ArrayList<>();
        legends.add("DIAPHRAGM_WALL");legends.add("BORED_PILE");
        legends.add("SMW_PILE");legends.add("JET_GROUTING_PILE");
        legends.add("MIXING_PILE");legends.add("DEWATERING_WELL");
        legends.add("EARTH_EXCAVATION");legends.add("STEEL_ERECTION");
        legends.add("CUSHION");legends.add("FLOOR");
        legends.add("MEDIUM_PLATE");legends.add("ROOF");

        String bidId = params.get("bidId")==null?"":params.get("bidId").toString().replace("null","");
        if(bidId.length() == 0){
            params.put("bidId",null);
        }
        params.put("source",1);
        List<String> xAxis = mainWorkScheduleMapper.getChartName(params);
        List<List<Double>> series = new ArrayList<>();
        List<List<Double>> current = new ArrayList<>();
        List<List<Double>> cumulative = new ArrayList<>();
        List<List<Double>> total = new ArrayList<>();
        for(int j = 0; j < legends.size(); j++){
            String subProjectName = legends.get(j);
            List<Double> ratetemp = new ArrayList<>();
            List<Double> curtemp = new ArrayList<>();
            List<Double> cumtemp = new ArrayList<>();
            List<Double> tottemp = new ArrayList<>();
            params.put("subProjectName",subProjectName);
            List<Map<String,Object>> mapList = mainWorkScheduleMapper.getChart(params);
            for(int i = 0; i < mapList.size(); i++){
                ratetemp.add(Double.valueOf(mapList.get(i).get("completeRate").toString()));
                curtemp.add(Double.valueOf(mapList.get(i).get("current").toString()));
                cumtemp.add(Double.valueOf(mapList.get(i).get("cumulative").toString()));
                tottemp.add(Double.valueOf(mapList.get(i).get("total").toString()));
            }
            series.add(ratetemp);
            current.add(curtemp);
            cumulative.add(cumtemp);
            total.add(tottemp);
        }
        res.put("legend",legend);
        res.put("xAxis",xAxis);
        res.put("series",series);
        res.put("current",current);
        res.put("cumulative",cumulative);
        res.put("total",total);
        return res;
    }

    public Map<String,Object> getChartBySite2(Map<String, Object> params)
    {
        Map<String,Object> res = new HashMap<>();
        List<String> xAxis = new ArrayList<>();
        xAxis.add("地下连续墙（幅）");xAxis.add("钻孔灌注桩（含格构柱）（根）");xAxis.add("咬合桩（根）");
        xAxis.add("SMW桩（根）");xAxis.add("旋喷桩（根）");
        xAxis.add("双/三轴搅拌桩（组）");xAxis.add("降水井（口）");
        xAxis.add("土方开挖（立方）");xAxis.add("钢支撑架设（根）");
        xAxis.add("垫层（段）");xAxis.add("底板（段）");
        xAxis.add("中板（段）");xAxis.add("顶板（段）");
        List<String> xAxiss = new ArrayList<>();
        xAxiss.add("DIAPHRAGM_WALL");xAxiss.add("BORED_PILE");
        xAxiss.add("SMW_PILE");xAxiss.add("JET_GROUTING_PILE");
        xAxiss.add("MIXING_PILE");xAxiss.add("DEWATERING_WELL");
        xAxiss.add("EARTH_EXCAVATION");xAxiss.add("STEEL_ERECTION");
        xAxiss.add("CUSHION");xAxiss.add("FLOOR");
        xAxiss.add("MEDIUM_PLATE");xAxiss.add("ROOF");
        String siteId = params.get("siteId")==null?"":params.get("siteId").toString();
        List<Double> series = new ArrayList<>();
        List<Double> current = new ArrayList<>();
        List<Double> cumulative = new ArrayList<>();
        List<Double> total = new ArrayList<>();
        String title = "";
        for(int i=0;i<xAxiss.size();i++){
            String subProjectName = xAxiss.get(i);
            HashMap<String,Object> param = new HashMap<>();
            param.put("subProjectName",subProjectName);
            param.put("siteId",siteId);
            param.put("source",1);
            Map<String,Object> map = mainWorkScheduleMapper.getChart(param).get(0);
            String completion = map.get("completeRate")==null?"0":map.get("completeRate").toString();
            String currentTemp = map.get("current")==null?"0":map.get("current").toString();
            String cumulativeTemp = map.get("cumulative")==null?"0":map.get("cumulative").toString();
            String totalTemp = map.get("total")==null?"0":map.get("total").toString();
            title = map.get("inOutSection")==null?"":map.get("inOutSection").toString();
            Double completeRate = Double.valueOf(completion);
            Double cur =Double.valueOf(currentTemp);
            Double cum =Double.valueOf(cumulativeTemp);
            Double tol =Double.valueOf(totalTemp);
            series.add(completeRate);
            current.add(cur);
            cumulative.add(cum);
            total.add(tol);
        }
        res.put("xAxis",xAxis);
        res.put("series",series);
        res.put("current",current);
        res.put("cumulative",cumulative);
        res.put("total",total);
        res.put("title",title);
        return res;
    }

    public boolean importSiteMainWorkSchedule(MultipartFile[] improtFiles,String loginId,ArrayList<SysDict> siteProjectNameList) throws IOException, ParseException {
        String failedFilename = null;
        String susscessFilename = null;
        for (MultipartFile file : improtFiles) {//循环

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream is = file.getInputStream();
            if (suffix.equalsIgnoreCase("xls")|| suffix.equalsIgnoreCase("xlsx") )//excel文件
            {
                List<Map<String, Object>> siteResultList = ExcelUtil.readFromSiteMainWorkScheduleExcel(fileName,is,siteProjectNameList);
                int beginindex = fileName.indexOf("（");
                if (beginindex == -1)
                    beginindex = fileName.indexOf("(");
                int endindex = fileName.indexOf("）");
                if (endindex == -1)
                    endindex = fileName.indexOf(")");
                String dateStr  = "";
                if (beginindex > 0 && endindex > beginindex)
                    dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                else
                {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    dateStr = formatter.format(new Date());
                }
                //log.info("#############关键信息################---mbResultList :"+ JSON.toJSONString());
                Map<String, Object> attachMap = null;
                if(siteResultList != null && siteResultList.size() > 0)//有数据，保存excel文件
                {
                    try {
                        is = file.getInputStream();
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String date = df.format(new Date());
                        String newFileName = fileUtil.uploadFile(is,fileName,date);

                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        paramMap.put("creator",loginId);
                        paramMap.put("uploader",loginId);
                        paramMap.put("name",newFileName);
                        paramMap.put("type","ATTACH_DOC");
                        paramMap.put("source","ATTACH_SITE_SCHEDULE");
                        attachMap = attachService.saveAttach(paramMap);
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                boolean sussb = siteResultToTable(siteResultList,suffix,dateStr,attachMap,loginId);
                if (!sussb && attachMap != null)
                {
                    attachService.deleteAttach(attachMap);
                }

                return sussb;
            }
        }
        return false;
    }
    public boolean siteResultToTable(List<Map<String, Object>> siteResultList,String suffix,String dateStr,Map<String, Object> attachMap,String loginId) {
        if (siteResultList == null || siteResultList.size() == 0)
            return false;

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("statisticsTime",dateStr);

        paramMap.put("source",0);
        List<Map<String,Object>> tempList = getMainWorkScheduleList(paramMap);
        if (tempList != null && tempList.size() > 0)
        {
            String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
            if (attachId != null)
            {
                paramMap.put("id",attachId);
                attachService.deleteAttach(paramMap);
            }
            mainWorkScheduleMapper.deleteMainWorkSchedule(paramMap);
        }


        for (int i = 0; i < siteResultList.size(); i++) {
            Map<String, Object> siteResultMap = siteResultList.get(i);
            Map<String, Object> siteMap = siteService.getSiteByName(siteResultMap.get("siteName").toString());
            if (siteMap == null)
                siteResultMap.put("siteId",null);
            else
                siteResultMap.put("siteId",siteMap.get("id"));

            Map<String, Object> bidMap = bidService.getBidByName(siteResultMap.get("bidName").toString());
            if (bidMap == null)
                siteResultMap.put("bidId",null);
            else
                siteResultMap.put("bidId",bidMap.get("id"));

            String  cumulative = siteResultMap.get("cumulative")==null?"":siteResultMap.get("cumulative").toString();
            String  total = siteResultMap.get("total")==null?"":siteResultMap.get("total").toString();
            String  completeRate = siteResultMap.get("completeRate")==null?"":siteResultMap.get("completeRate").toString();
            if (completeRate.length()==0 && cumulative.length() > 0 && total.length() > 0)
            {
                DecimalFormat df = new DecimalFormat("0.0");//格式化小数
                completeRate = df.format((float)(Float.parseFloat(cumulative)*100)/Float.parseFloat(total));//返回的是String类型
                siteResultMap.put("completeRate",completeRate);
            }
            siteResultMap.put("attachId",attachMap.get("id"));
            siteResultMap.put("statisticsTime",dateStr);
            siteResultMap.put("creator",loginId);
            mainWorkScheduleMapper.insertMainWorkSchedule(siteResultMap);
        }
        return true;
    }

    public boolean importSectionMainWorkSchedule(MultipartFile[] improtFiles,String loginId,ArrayList<SysDict> siteProjectNameList) throws IOException, ParseException {
        String failedFilename = null;
        String susscessFilename = null;
        for (MultipartFile file : improtFiles) {//循环

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream is = file.getInputStream();
            if (suffix.equalsIgnoreCase("xls")|| suffix.equalsIgnoreCase("xlsx") )//excel文件
            {
                List<Map<String, Object>> sectionResultList = ExcelUtil.readFromSectionMainWorkScheduleExcel(fileName,is,siteProjectNameList);
                int beginindex = fileName.indexOf("（");
                if (beginindex == -1)
                    beginindex = fileName.indexOf("(");
                int endindex = fileName.indexOf("）");
                if (endindex == -1)
                    endindex = fileName.indexOf(")");
                String dateStr  = "";
                if (beginindex > 0 && endindex > beginindex)
                    dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                else
                {
                    /*SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    dateStr = formatter.format(new Date());*/
                    return  false;
                }
                //log.info("#############关键信息################---mbResultList :"+ JSON.toJSONString());
                Map<String, Object> attachMap = null;
                if(sectionResultList != null && sectionResultList.size() > 0)//有数据，保存excel文件
                {
                    try {
                        is = file.getInputStream();
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String date = df.format(new Date());
                        String newFileName = fileUtil.uploadFile(is,fileName,date);

                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        paramMap.put("creator",loginId);
                        paramMap.put("uploader",loginId);
                        paramMap.put("name",newFileName);
                        paramMap.put("type","ATTACH_DOC");
                        paramMap.put("source","ATTACH_SECTION_SCHEDULE");
                        attachMap = attachService.saveAttach(paramMap);
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                boolean sussb = sectionResultToTable(sectionResultList,suffix,dateStr,attachMap,loginId);
                if (!sussb && attachMap != null)
                {
                    attachService.deleteAttach(attachMap);
                }

                return sussb;
            }
        }
        return false;
    }

    public boolean sectionResultToTable(List<Map<String, Object>> sectionResultList,String suffix,String dateStr,Map<String, Object> attachMap,String loginId) {
        if (sectionResultList == null || sectionResultList.size() == 0)
            return false;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("statisticsTime",dateStr);

        paramMap.put("source",1);
        List<Map<String,Object>> tempList = getMainWorkScheduleList(paramMap);
        if (tempList != null && tempList.size() > 0)
        {
            String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
            if (attachId != null)
            {
                paramMap.put("id",attachId);
                attachService.deleteAttach(paramMap);
            }
            mainWorkScheduleMapper.deleteMainWorkSchedule(paramMap);
        }

        for (int i = 0; i < sectionResultList.size(); i++) {
            Map<String, Object> sectionResultMap = sectionResultList.get(i);

            Map<String, Object> bidMap = bidService.getBidByName(sectionResultMap.get("bidName").toString());
            if (bidMap == null)
                sectionResultMap.put("bidId",null);
            else
                sectionResultMap.put("bidId",bidMap.get("id"));

            String  cumulative = sectionResultMap.get("cumulative")==null?"":sectionResultMap.get("cumulative").toString();
            String  total = sectionResultMap.get("total")==null?"":sectionResultMap.get("total").toString();
            String  completeRate = sectionResultMap.get("completeRate")==null?"":sectionResultMap.get("completeRate").toString();
            if (completeRate.length()==0 && cumulative.length() > 0 && total.length() > 0)
            {
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                completeRate = df.format((float)(Float.parseFloat(cumulative)*100)/Float.parseFloat(total));//返回的是String类型
                sectionResultMap.put("completeRate",completeRate);
            }
            sectionResultMap.put("attachId",attachMap.get("id"));
            sectionResultMap.put("statisticsTime",dateStr);
            sectionResultMap.put("creator",loginId);
            mainWorkScheduleMapper.insertMainWorkSchedule(sectionResultMap);
        }
        return true;
    }



    public List<List<Map<String,Object>>> getSiteTable(Map<String, Object> params)
    {
        List<List<Map<String,Object>>> res = new ArrayList<>();
        List<Map<String,Object>> siteList = siteService.getSiteListNoPage(null);
        for(int i=0;i<siteList.size();i++){
            Long siteId = Long.valueOf(siteList.get(i).get("id").toString());
            Map<String,Object> param = new HashMap<>();
            param.put("siteId",siteId);
            param.put("source",0);
            param.put("isSum",0);
            List<Map<String,Object>> list = mainWorkScheduleMapper.getChart(param);
            res.add(list);
        }
        Map<String,Object> sumParam = new HashMap<>();
        sumParam.put("source",0);
        sumParam.put("isSum",1);
        List<Map<String,Object>> list = mainWorkScheduleMapper.getChart(sumParam);
        res.add(list);
        return res;
    }

    public List<List<Map<String,Object>>> getSectionTable(Map<String, Object> params)
    {
        List<List<Map<String,Object>>> res = new ArrayList<>();
        List<Map<String,Object>> siteList = siteService.getSiteListNoPage(null);
        for(int i=0;i<siteList.size();i++){
            Long siteId = Long.valueOf(siteList.get(i).get("id").toString());
            Map<String,Object> param = new HashMap<>();
            param.put("siteId",siteId);
            param.put("source",1);
            param.put("isSum",0);
            List<Map<String,Object>> list = mainWorkScheduleMapper.getChart(param);
            res.add(list);
        }
        Map<String,Object> sumParam = new HashMap<>();
        sumParam.put("source",1);
        sumParam.put("isSum",1);
        List<Map<String,Object>> list = mainWorkScheduleMapper.getChart(sumParam);
        res.add(list);
        return res;
    }

    public List<Map<String,Object>> getTime(Map<String, Object> params){
        return mainWorkScheduleMapper.getTime(params);
    }

    public List<Map<String,Object>> getHistoryAttach(Map<String, Object> params){
        return mainWorkScheduleMapper.getHistoryAttach(params);
    }

    public Double siteCompleteRateAvg(Map<String,Object> params){
        Double d = mainWorkScheduleMapper.siteCompleteRateAvg(params);
        if (d==null)
            d = 0.0;
        return d;
    }

    public Double sectionCompleteRateAvg(Map<String,Object> params){
        Double d = mainWorkScheduleMapper.sectionCompleteRateAvg(params);
        if (d==null)
            d = 0.0;
        return d;

    }

    public Double mainProjectCompleteRateAvg(Map<String,Object> params){
        Double d = mainWorkScheduleMapper.mainProjectCompleteRateAvg(params);
        if (d==null)
            d = 0.0;
        return d;
    }

    public List<Map<String,Object>> getXAxisNum(Map<String,Object> params){
        return mainWorkScheduleMapper.getXAxisNum(params);
    }
}
